package com.chinacoal.microservice.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.plugins.Page;
import com.chinacoal.microservice.mapper.CcmsSmartleasingAssessmentMapper;
import com.chinacoal.microservice.mapper.CcmsSmartleasingAssessmentScoreMapper;
import com.chinacoal.microservice.mapper.CcmsSmartleasingAssessorMapper;
import com.chinacoal.microservice.mapper.CcmsSmartleasingIndicatorProportMapper;
import com.chinacoal.microservice.pojo.AssessmentStatistics;
import com.chinacoal.microservice.pojo.CcmsSmartleasingAssessment;
import com.chinacoal.microservice.pojo.CcmsSmartleasingAssessmentScore;
import com.chinacoal.microservice.pojo.CcmsSmartleasingAssessor;
import com.chinacoal.microservice.pojo.CcmsSmartleasingIndicatorProport;
import com.chinacoal.microservice.pojo.CcmsSmartleasingIndicatorProportVO;
import com.chinacoal.microservice.pojo.Currency;
import com.chinacoal.microservice.pojo.ExcelAssessmentStatistics;
import com.chinacoal.microservice.service.AssessmentService;
import com.chinacoal.microservice.util.ExcelUtils;
import com.chinacoal.microservice.util.QueryCriteria;
import com.chinacoal.microservice.util.Result;

/**
 * 考核模块-考核管理业务实现层
 * @author wiilead
 *
 */
@Service
public class AssessmentServiceImpl implements AssessmentService {
    @Autowired
    private CcmsSmartleasingAssessmentMapper ccmsSmartleasingAssessmentMapper;
    
    @Autowired
    private CcmsSmartleasingIndicatorProportMapper smartleasingIndicatorProportMapper;
    
    @Autowired
    private CcmsSmartleasingAssessmentScoreMapper smartleasingAssessmentScoreMapper;
    
    @Autowired
    private CcmsSmartleasingAssessorMapper smartleasingAssessorMapper;
    
    @Autowired
	private RedisTemplate redisTemplate;
	
    /**
     * 新增或修改考核信息
     */
	@Override
	public Result addOrUpdateAssessment(CcmsSmartleasingAssessment assessment, String token) {
		// TODO Auto-generated method stub
		//得到登录人id,并做兼容性处理
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }
        
        if(StringUtils.isEmpty(assessment.getAssessmentId())) { //新增
        	assessment.setAssessmentId(UUID.randomUUID() + "");
        	assessment.setCreatedBy(currency.getLoginId());
        	assessment.setCreationDate(new Date());
        	assessment.setLastUpdatedBy(currency.getLoginId());
        	assessment.setLastUpdateDate(new Date());
        	
        	//新增考核信息
        	ccmsSmartleasingAssessmentMapper.insert(assessment);
        	
        	//新增该考核多个考核人
        	for(CcmsSmartleasingAssessor assessor:assessment.getAssessorList()) {
        		assessor.setId(UUID.randomUUID() + "");
        		assessor.setAssessmentId(assessment.getAssessmentId());
        		
        		smartleasingAssessorMapper.insert(assessor);
        	}
        	
        	//新增该考核中指标项占比
        	for(CcmsSmartleasingIndicatorProportVO indicatorProportVO:assessment.getIndicatorList()) {
        		CcmsSmartleasingIndicatorProport indicatorProport = new CcmsSmartleasingIndicatorProport();
        		indicatorProport.setId(UUID.randomUUID() + "");
        		indicatorProport.setIndicatorId(indicatorProportVO.getIndicatorId());
        		indicatorProport.setProportion(indicatorProportVO.getProportion());
        		indicatorProport.setActualCompletion(indicatorProportVO.getActualCompletion());
        		indicatorProport.setAssessmentId(assessment.getAssessmentId());
        		indicatorProport.setCreatedBy(currency.getLoginId());
        		indicatorProport.setCreationDate(new Date());
        		indicatorProport.setLastUpdatedBy(currency.getLoginId());
        		indicatorProport.setLastUpdateDate(new Date());
        		
        		smartleasingIndicatorProportMapper.insert(indicatorProport);
        	}
        }else { //修改
        	assessment.setLastUpdatedBy(currency.getLoginId());
        	assessment.setLastUpdateDate(new Date());
        	
        	//修改考核信息
        	ccmsSmartleasingAssessmentMapper.updateAssessment(assessment);
        	
        	//全量删除考核人明细
        	smartleasingAssessorMapper.deleteByAssessmentId(assessment.getAssessmentId());
        	//全量新增该考核多个考核人
        	for(CcmsSmartleasingAssessor assessor:assessment.getAssessorList()) {
        		assessor.setId(UUID.randomUUID() + "");
        		assessor.setAssessmentId(assessment.getAssessmentId());
        		
        		smartleasingAssessorMapper.insert(assessor);
        	}
        	
        	//全量删除指标项占比
        	smartleasingIndicatorProportMapper.deleteByAssessmentId(assessment.getAssessmentId());
        	//全量新增该考核中指标项占比
        	for(CcmsSmartleasingIndicatorProportVO indicatorProportVO:assessment.getIndicatorList()) {
        		CcmsSmartleasingIndicatorProport indicatorProport = new CcmsSmartleasingIndicatorProport();
        		indicatorProport.setId(UUID.randomUUID() + "");
        		indicatorProport.setIndicatorId(indicatorProportVO.getIndicatorId());
        		indicatorProport.setProportion(indicatorProportVO.getProportion());
        		indicatorProport.setActualCompletion(indicatorProportVO.getActualCompletion());
        		indicatorProport.setAssessmentId(assessment.getAssessmentId());
        		indicatorProport.setCreatedBy(currency.getLoginId());
        		indicatorProport.setCreationDate(new Date());
        		indicatorProport.setLastUpdatedBy(currency.getLoginId());
        		indicatorProport.setLastUpdateDate(new Date());
        		
        		smartleasingIndicatorProportMapper.insert(indicatorProport);
        	}
        }
		return Result.success();
	}

	/**
	 * 考核列表
	 */
	@Override
	public Result<List<CcmsSmartleasingAssessment>> getAssessmentList(QueryCriteria queryCriteria,String token) {
		// TODO Auto-generated method stub
		//得到登录人id,并做兼容性处理
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }
        
        Page<CcmsSmartleasingAssessment> toPage = new Page<>(queryCriteria.getPage(),queryCriteria.getPageSize());
        

    	List<String> assessmentIdList = smartleasingAssessorMapper.selectAssessmentIdList(currency.getLoginId());
    	List<CcmsSmartleasingAssessment> assessmentList = ccmsSmartleasingAssessmentMapper.selectAssessmentList(toPage,queryCriteria.getType(),
    																	assessmentIdList,currency.getLoginId());
		for(CcmsSmartleasingAssessment assessment:assessmentList) {
			//查询考核人明细
			assessment.setAssessorList(smartleasingAssessorMapper.selectAssessorList(assessment.getAssessmentId()));	
		}
		
		return Result.success(assessmentList, toPage.getTotal());
	}

	/**
	 * 查询考核详情
	 */
	@Override
	public Result<CcmsSmartleasingAssessment> getAssessmentInfo(String assessmentId,String token) {
		// TODO Auto-generated method stub
		//得到登录人id,并做兼容性处理
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }
		        
		CcmsSmartleasingAssessment assessment = ccmsSmartleasingAssessmentMapper.selectAssessmentInfo(assessmentId);
		
		//查询考核人明细
		assessment.setAssessorList(smartleasingAssessorMapper.selectAssessorList(assessmentId));
		
//		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		//查询指标项信息
		List<CcmsSmartleasingIndicatorProportVO> indicatorProportVOList = smartleasingIndicatorProportMapper
																.selectIndicatorProportByAssessmentId(assessmentId,currency.getLoginId());
//		for(CcmsSmartleasingIndicatorProportVO indicatorProportVO:indicatorProportVOList) {
//			Map<String, Object> map = new HashMap<String, Object>();
//			List<CcmsSmartleasingIndicatorProportVO> childTndicatorProportList =  new ArrayList<>();
//			
//			//将同一父级指标项放入同一list中
//			for(CcmsSmartleasingIndicatorProportVO indicatorProportVO2:indicatorProportVOList) {
//				if(indicatorProportVO.getParentId().equals(indicatorProportVO2.getParentId())) {
//					childTndicatorProportList.add(indicatorProportVO2);
//					continue;
//				}
//			}
//			
//			//父级是否已存在
//			boolean isRet = false;
//			for(Map<String, Object> hashMap:list) {
//				if(indicatorProportVO.getParentName().equals(hashMap.get("parentName").toString())){
//					isRet = true;
//					break;
//				}
//			}
//			
//			if(!isRet) {
//				map.put("parentName", indicatorProportVO.getParentName());
//				map.put("childTndicatorProportList", childTndicatorProportList);
//				list.add(map);
//			}
//		}
		
		assessment.setIndicatorList(indicatorProportVOList);
		
		return Result.success(assessment);
	}

	/**
	 * 删除考核
	 */
	@Override
	public Result deleteAssessment(String assessmentId) {
		// TODO Auto-generated method stub
		ccmsSmartleasingAssessmentMapper.deleteAssessment(assessmentId);
		return Result.success();
	}

	/**
	 * 考核
	 */
	@Override
	public Result addAssessmentScore(List<CcmsSmartleasingAssessmentScore> assesmentScoreList,String token) {
		// TODO Auto-generated method stub
		//得到登录人id,并做兼容性处理
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }
		
        String assessmentId = "";
        for(CcmsSmartleasingAssessmentScore assessmentScore:assesmentScoreList) {
        	assessmentId = assessmentScore.getAssessmentId();
        	assessmentScore.setId(UUID.randomUUID() + "");
    		assessmentScore.setCreatedBy(currency.getLoginId());
    		assessmentScore.setCreationDate(new Date());
    		assessmentScore.setLastUpdatedBy(currency.getLoginId());
    		assessmentScore.setLastUpdateDate(new Date());
    		smartleasingAssessmentScoreMapper.insert(assessmentScore);
        }
        
        //判断考核人是否已全部打分
        Integer assessorCount = smartleasingAssessorMapper.statisticsAssessor(assessmentId);
        Integer raterCount = smartleasingAssessmentScoreMapper.statisticsRater(assessmentId);
        if(assessorCount==raterCount) {
        	//统计得分
        	//1.获取考核人占比
        	List<CcmsSmartleasingAssessor> assessorList = smartleasingAssessorMapper.selectAssessorList(assessmentId);
        	//3.获取考核人打分
        	List<CcmsSmartleasingAssessmentScore> assessmentScoreList = smartleasingAssessmentScoreMapper.selectScoreByAssessmentId(assessmentId);
        	
        	Double totalScore = 0.0; //总得分
        	for(CcmsSmartleasingAssessor assessor:assessorList) {
        		Double indicatorTotalScore = 0.0; //指标项总得分
        		for(CcmsSmartleasingAssessmentScore assessmentScore:assessmentScoreList) {
        			if(assessor.getAssessor().equals(assessmentScore.getCreatedBy())) {
        				indicatorTotalScore += assessmentScore.getScore();
        			}
            	}
        		totalScore += indicatorTotalScore*assessor.getProportion()/100;
        	}
        	
        	ccmsSmartleasingAssessmentMapper.updateAssessmentTotalScore(totalScore, assessmentId);
        }
		
		return Result.success();
	}
	
	/**
	 * 考核统计
	 */
	@Override
	public Result<List<AssessmentStatistics>> getAssessmentSatistics(QueryCriteria queryCriteria) {
		// TODO Auto-generated method stub
		Page<AssessmentStatistics> toPage = new Page<>(queryCriteria.getPage(),queryCriteria.getPageSize());
		
		List<AssessmentStatistics> assessmentStatisticList = ccmsSmartleasingAssessmentMapper.statisticsAssessmentList(toPage, queryCriteria.getType());
		
		return Result.success(assessmentStatisticList,toPage.getTotal());
	}

	/**
	 * 考核统计导出
	 */
	@Override
	public void exportExcel(HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		OutputStream os = response.getOutputStream();// 取得输出流
		response.reset();// 清空输出流
		response.setHeader("Content-disposition", "attachment; filename="
          + new String("考核排行.xls".getBytes("GB2312"), "ISO8859-1"));
		// 设定输出文件头
		response.setContentType("application/msexcel");// 定义输出类型
		
		List<List<String>> data1 = new ArrayList<List<String>>();
        List<List<String>> data2 = new ArrayList<List<String>>();
		
		Page<AssessmentStatistics> toPage = new Page<>(1,1000);
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//经理考核统计
		List<AssessmentStatistics> managerAssessmentStatisticList = ccmsSmartleasingAssessmentMapper.statisticsAssessmentList(toPage, 1);
		for(AssessmentStatistics statistics:managerAssessmentStatisticList) {
			List rowData = new ArrayList();
			rowData.add(statistics.getAssesseeName());
			rowData.add(statistics.getScore()+"");
			rowData.add(statistics.getName());
			rowData.add(sf.format(statistics.getStartDate())+"到"+sf.format(statistics.getEndDate()));
			data1.add(rowData);
		}
		//员工考核统计
		List<AssessmentStatistics> staffAssessmentStatisticList = ccmsSmartleasingAssessmentMapper.statisticsAssessmentList(toPage, 2);
		for(AssessmentStatistics statistics:staffAssessmentStatisticList) {
			List rowData = new ArrayList();
			rowData.add(statistics.getAssesseeName());
			rowData.add(statistics.getScore()+"");
			rowData.add(statistics.getName());
			rowData.add(sf.format(statistics.getStartDate())+"到"+sf.format(statistics.getEndDate()));
			data2.add(rowData);
		}
		
		String[] headers = { "人员", "得分", "考核名称", "考核时间"}; 
		ExcelUtils excelUtils = new ExcelUtils();
		HSSFWorkbook workbook = new HSSFWorkbook();
		excelUtils.exportExcel(workbook, 0, "部门正职排行", headers, data1, os);
		excelUtils.exportExcel(workbook, 1, "其他排行", headers, data2, os);
		//将所有的数据一起写入，然后再关闭输入流。  
        workbook.write(os);  
        os.close();  
	}
}
